import 'package:fluent_ui/fluent_ui.dart';
import 'package:multi_select_flutter/util/multi_select_item.dart';
import 'package:super_timetable_front/global_setting.dart';

import '../../api/school_api.dart';
import '../../components/data_table.dart';
import '../../model/school_model.dart';
import '../../utils/loading_utils.dart';
import '../app/app_dict_data.dart';

abstract class SchoolField {}

///学校:查询字段
enum SchoolQueryField implements SchoolField {
  name('名称/标题'),
  stages('学段'),
  status('状态');

  final String label;

  const SchoolQueryField(this.label);
}

///学校:输入字段
enum SchoolInputField implements SchoolField {
  name('名称', checked: true),
  remark('描述'),
  stages('学段', checked: true),
  status('状态', isAdd: false);

  final String label;
  final bool checked, isAdd;

  const SchoolInputField(
    this.label, {
    this.checked = false,
    this.isAdd = true,
  });

  String? validHandler<T>(final T? val) {
    if (checked) {
      if (val == null) {
        return '$label不能为空';
      }
      if (val is String) {
        return val.isEmpty ? '$label不能为空' : null;
      }
      if (val is List) {
        return val.isEmpty ? '$label不能为空' : null;
      }
    }
    return null;
  }
}

///学校:视图模型
class SchoolViewModel extends ChangeNotifier {
  //查询字段
  final _queryFields = <SchoolQueryField, TextEditingController>{
    for (var field in SchoolQueryField.values) field: TextEditingController(),
  };

  //输入字段
  final _inputFields = <SchoolInputField, TextEditingController>{
    for (var field in SchoolInputField.values) field: TextEditingController(),
  };

  //获取控制器
  TextEditingController? getController<T extends SchoolField>(final T field) {
    //查询字段
    if (field is SchoolQueryField) {
      return _queryFields[field];
    }
    //输入字段
    if (field is SchoolInputField) {
      return _inputFields[field];
    }
    return null;
  }

  ///获取字段值
  String? getFieldValue<T extends SchoolField>(final T field) {
    final ctr = getController(field);
    if (ctr != null) {
      return ctr.text;
    }
    return null;
  }

  void setFieldValue<T extends SchoolField>(T field, String? val) {
    final controller = getController(field);
    if (controller != null) {
      controller.text = val ?? '';
    }
  }

  final _statusOpts = <ComboBoxItem<String>>[];

  final _stageOpts = <MultiSelectItem<int>>[];

  ///获取状态选项集合
  List<ComboBoxItem<String>> get statusOpts => _statusOpts;

  ///获取学段选项集合
  List<MultiSelectItem<int>> get stageOpts => _stageOpts;

  ///加载字典
  void _loadDict(final List<Future<dynamic>> futures) {
    //状态
    if (_statusOpts.isEmpty) {
      final future = appDictData.buildOpts('status').then((opts) {
        if (opts.isNotEmpty) {
          _statusOpts.addAll(opts);
        }
      });
      futures.add(future);
    }
    //学段
    if (_stageOpts.isEmpty) {
      final future = appDictData.itemsByCode('stage').then((stages) {
        if (stages.isNotEmpty) {
          for (var model in stages) {
            final int? val = int.tryParse(model.val);
            if (val != null && val >= 0) {
              stageOpts.add(MultiSelectItem<int>(val, model.label));
            }
          }
        }
      });
      futures.add(future);
    }
  }

  ///加载初始化
  void loadInit({final VoidCallback? afterHandler}) async {
    final futures = <Future<dynamic>>[];
    //加载字典
    _loadDict(futures);
    //请求同步
    if (futures.isNotEmpty) {
      await Future.wait(futures);
      notifyListeners();
    }
    //回调处理
    if (afterHandler != null) {
      afterHandler.call();
    }
  }

  ///清空查询字段
  void cleanQueryFields() {
    for (var ctl in _queryFields.values) {
      ctl.clear();
    }
  }

  ///清空输入字端
  void cleanInputFields() {
    for (var ctl in _inputFields.values) {
      ctl.clear();
    }
  }

  ///分页查询模型
  final queryModel = PageModel<SchoolItemRes>();

  ///学段拆分
  List<int> stageSplits(final String? stages) {
    final rows = <int>[];
    if (stages != null && stages.isNotEmpty) {
      final items = stages.split(',');
      if (items.isNotEmpty) {
        for (var item in items) {
          final int? val = int.tryParse(item);
          if (val != null && val >= 0) {
            if (!rows.contains(val)) {
              rows.add(val);
            }
          }
        }
      }
    }
    return rows;
  }

  ///学段拼接
  String stageJoins(final List<int>? stages) {
    if (stages != null && stages.isNotEmpty) {
      return stages.join(',');
    }
    return '';
  }

  ///分页查询
  void query() async {
    try {
      loading.showLoading();
      //查询条件
      final status = getFieldValue(SchoolQueryField.status);
      final stages = getFieldValue(SchoolQueryField.stages);
      final req = SchoolQueryReq(
        tenantId: globalSetting.tenant,
        name: getFieldValue(SchoolQueryField.name) ?? '',
        stages: stageSplits(stages),
        status: int.tryParse(status ?? '') ?? -1,
        index: queryModel.current,
        size: queryModel.size,
      );
      final res = await schoolApi.query(req);
      if (res.isSuccessed) {
        queryModel.buildResData(res);
      }
      debugPrint('schoolApi.query(req:${req.toMap()})=>$res');
    } finally {
      loading.dismiss();
    }
  }

  ///加载数据
  void getInfoById(final String id) async {
    try {
      loading.showLoading();
      //加载数据
      final res = await schoolApi.info(id);
      if (res.isSuccessed) {
        setFieldValue(SchoolInputField.name, res.name);
        setFieldValue(SchoolInputField.remark, res.remark);
        setFieldValue(SchoolInputField.stages, stageJoins(res.stages));
        setFieldValue(SchoolInputField.status, '${res.status}');
        //触发处理
        notifyListeners();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///新增处理
  void onAddHandler(final VoidCallback handler) async {
    try {
      loading.showLoading();
      //新增处理
      final stages = getFieldValue(SchoolInputField.stages) ?? '';
      final name = getFieldValue(SchoolInputField.name) ?? '';
      final req = SchoolAddReq(
        tenantId: globalSetting.tenant,
        name: name,
        remark: getFieldValue(SchoolInputField.remark) ?? '',
        stages: stageSplits(stages),
      );
      //提交
      final res = await schoolApi.add(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///修改处理
  void onModifyHandler(final String id, final VoidCallback handler) async {
    try {
      loading.showLoading();
      //修改处理
      final stages = getFieldValue(SchoolInputField.stages);
      final status = getFieldValue(SchoolInputField.status);
      final req = SchoolModifyReq(
        id: id,
        name: getFieldValue(SchoolInputField.name) ?? '',
        remark: getFieldValue(SchoolInputField.remark) ?? '',
        stages: stageSplits(stages ?? ''),
        status: int.tryParse(status ?? '') ?? 1,
      );
      //提交
      final res = await schoolApi.modify(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///删除处理
  void onDeleteHandler(final String id) async {
    try {
      loading.showLoading();
      //删除
      final res = await schoolApi.delete(id);
      if (res.isSuccessed) {
        query();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }
}
